package com.xiaozhen.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.xiaozhen.common.core.constant.Constants;
import com.xiaozhen.common.core.constant.UserConstants;
import com.xiaozhen.security.controller.BaseController;
import com.xiaozhen.common.core.domain.AjaxResult;
import com.xiaozhen.common.core.domain.system.SysMenu;
import com.xiaozhen.common.core.domain.system.queryParams.SysMenuQueryParam;
import com.xiaozhen.common.core.utils.StringUtils;
import com.xiaozhen.system.service.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/8/18 11:58
 * @description:
 */
@RestController
@Api(tags = "系统菜单接口")
@RequestMapping("/sysMenu")
public class SysMenuController extends BaseController {

    @Autowired
    private SysMenuService sysMenuService;

    @ApiOperation("获取路由信息")
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = getCurrentUserId();
        List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(sysMenuService.buildMenus(menus));
    }

    @ApiOperation("获取菜单列表")
    @GetMapping("/list")
    @SaCheckPermission("system:menu:list")
    public AjaxResult list(SysMenuQueryParam queryParam) {
        List<SysMenu> menus = sysMenuService.selectMenuList(queryParam, getCurrentUserId());
        return AjaxResult.success(menus);
    }

    @ApiOperation("添加菜单")
    @PostMapping("/add")
    @SaCheckPermission("system:menu:add")
    public AjaxResult add(@Validated @RequestBody SysMenu sysMenu) {
        if (!sysMenuService.checkMenuNameUnique(sysMenu)) {
            return AjaxResult.error("新增菜单'" + sysMenu.getMenuName() + "'失败，菜单名称已存在");
        }
        if (UserConstants.YES_FRAME.equals(sysMenu.getIsFrame())
                && !StringUtils.startsWithAny(sysMenu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return AjaxResult.error("新增菜单'" + sysMenu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        sysMenu.setCreateBy(getCurrentUserId());
        sysMenu.setCreateTime(LocalDateTime.now());
        return toAjax(sysMenuService.insertMenu(sysMenu));
    }

    @ApiOperation("修改菜单")
    @PutMapping("/update")
    @SaCheckPermission("system:menu:update")
    public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
        if (!sysMenuService.checkMenuNameUnique(menu)) {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        if (menu.getMenuId().equals(menu.getParentId())) {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(getCurrentUserId());
        menu.setUpdateTime(LocalDateTime.now());
        return toAjax(sysMenuService.updateMenu(menu));
    }

    @ApiOperation("删除菜单")
    @DeleteMapping("/{menuId}")
    @SaCheckPermission("system:menu:delete")
    public AjaxResult remove(@PathVariable("menuId") Long menuId) {
        if (sysMenuService.hasChildByMenuId(menuId)) {
            return AjaxResult.error("存在子菜单,不允许删除");
        }
        if (sysMenuService.checkMenuExistRole(menuId)) {
            return AjaxResult.error("菜单已分配,不允许删除");
        }
        return toAjax(sysMenuService.deleteMenuById(menuId));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeSelect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysMenu> menus = sysMenuService.selectMenuList(getCurrentUserId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", sysMenuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", menus);
        return ajax;
    }
}
